package com.mfc.ctrl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mfc.cons.Sys;
import com.mfc.entity.InventoryInbound;
import com.mfc.entity.Medicine;
import com.mfc.service.InventoryInboundService;
import com.mfc.service.MedicineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/jsp/detail")
public class   InDetailController {

	@Autowired
	private InventoryInboundService inboundService;

	@Autowired
	private MedicineService medicineService;

	@RequestMapping("/page")
	public String page(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			, InventoryInbound o, Model model) {
		PageHelper.startPage(pageNo,Sys.pageSize," id desc ");
		o.setIoType(1);
		List<InventoryInbound> li = inboundService.list(o);
		PageInfo<InventoryInbound> pageInfo=new PageInfo<InventoryInbound>(li, Sys.pageSize);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("o", o);
		return Sys.jsp+"/detail_page";
	}

	@RequestMapping("/del")
	public String del(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,InventoryInbound o,Model model) {
		try {
			inboundService.delete(o.getId());
		} catch (Exception e) {
			model.addAttribute("msg", "请先删除该库存关联的其他信息");
			return "forward:/"+Sys.jsp+"/detail/page?pageNo="+pageNo;
		}
		return "redirect:/"+Sys.jsp+"/detail/page?pageNo="+pageNo;
	}

	/**
	 * 入库
	 */
	@RequestMapping("/save")
	public String save(@RequestParam(value="pageNo",defaultValue="1")int pageNo
			,InventoryInbound o,Model model) {

		Medicine medicine = null;
		List<Medicine> i = medicineService.list(new Medicine().setMedicineId(o.getDrugId()));
		if (i!=null && i.size()!=0){
			medicine = i.get(0);
			inboundService.insert(o);
			medicine.setStockQuantity(medicine.getStockQuantity()+o.getInboundQuantity());
			medicineService.update(new Medicine().setStockQuantity(medicine.getStockQuantity()).setMedicineId(medicine.getMedicineId()));
		}
		return "redirect:/"+Sys.jsp+"/detail/page?pageNo="+pageNo;
	}

}
